// 购物车模块
export default {
  namespaced: true, // 启用命名空间
  
  state: {
    items: [],
    total: 0,
    discount: 0
  },
  
  getters: {
    // 计算购物车总价
    cartTotal(state) {
      return state.items.reduce((total, item) => total + (item.price * item.quantity), 0)
    },
    
    // 计算折扣后价格
    discountedTotal(state, getters) {
      return getters.cartTotal * (1 - state.discount / 100)
    },
    
    // 获取购物车商品数量
    itemCount(state) {
      return state.items.reduce((count, item) => count + item.quantity, 0)
    }
  },
  
  mutations: {
    // 添加商品到购物车
    addItem(state, item) {
      const existingItem = state.items.find(i => i.id === item.id)
      if (existingItem) {
        existingItem.quantity += item.quantity
      } else {
        state.items.push(item)
      }
    },
    
    // 从购物车移除商品
    removeItem(state, itemId) {
      state.items = state.items.filter(item => item.id !== itemId)
    },
    
    // 更新商品数量
    updateQuantity(state, { itemId, quantity }) {
      const item = state.items.find(i => i.id === itemId)
      if (item) {
        item.quantity = quantity
      }
    },
    
    // 设置折扣
    setDiscount(state, discount) {
      state.discount = discount
    },
    
    // 清空购物车
    clearCart(state) {
      state.items = []
      state.discount = 0
    }
  },
  
  actions: {
    // 异步添加商品到购物车
    async addToCart({ commit }, item) {
      // 模拟 API 调用
      return new Promise((resolve) => {
        setTimeout(() => {
          commit('addItem', item)
          resolve({ success: true, message: '商品已添加到购物车' })
        }, 300)
      })
    },
    
    // 异步清空购物车
    async clearCartAsync({ commit }) {
      // 模拟 API 调用
      return new Promise((resolve) => {
        setTimeout(() => {
          commit('clearCart')
          resolve({ success: true, message: '购物车已清空' })
        }, 500)
      })
    }
  }
}